package com.scau.jansing.thread.first.resource;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by jansing on 2015/12/2.
 */
public class EvenGenerator extends IntGenerator{
//    private int currentEvenValue = 0;

    //1、无任何措施，此时会紊乱
//    @Override
//    public int next() {
//        currentEvenValue++;
//        Thread.yield();
//        currentEvenValue++;
//        return currentEvenValue;
//    }

    //2、使用synchronized
//    @Override
//    public synchronized int next() {
//        currentEvenValue++;
//        Thread.yield();
//        currentEvenValue++;
//        return currentEvenValue;
//    }


    //3、使用lock
//    private Lock lock = new ReentrantLock();
//    @Override
//    public int next() {
//        lock.lock();
//        try {
//            currentEvenValue++;
//            Thread.yield();
//            currentEvenValue++;
//            return currentEvenValue;
//        }finally {
//            lock.unlock();
//        }
//    }

    //4、使用原子操作
    private AtomicInteger currentEvenValue = new AtomicInteger(0);
    @Override
    public int next() {
        return currentEvenValue.addAndGet(2);
    }

    public static void main(String[] args){
        EvenChecker.test(new EvenGenerator());
    }
}
